﻿using LuaInterface;
using System;
using UnityEngine;

public class CameraCtrl : MonoBehaviour
{
	[NoToLua]
	public bool mCanMove;
	[NoToLua]
	public float speed = 0.02f;

	private bool isFlag = false;
	private Vector3 lastPos;
	private Vector3 curPos;
	Vector3 forward;
	Vector3 right;
	Action updateCallback;
	private void Awake()
	{
		forward = transform.forward;
		forward.y = 0;
		forward.Normalize();
		right = transform.right;
	}
	public void SetMove(bool canMove)
	{
		mCanMove = canMove;
	}
	public void Set(Action updateCallback, float speed = 0.02f)
	{
		this.speed = speed;
		this.updateCallback = updateCallback;
	}
    void LateUpdate()
    {
		if (!mCanMove) return;
#if UNITY_EDITOR
		if (Input.GetMouseButton(0))
		{
			if (!isFlag)
			{
				isFlag = true;
				lastPos = Input.mousePosition;
			}
			curPos = Input.mousePosition;
		}
		if (Input.GetMouseButtonUp(0))
		{
			isFlag = false;
			mCanMove = false;
			return;
		}
#endif
		if (lastPos == curPos) return;
		Vector3 dir = lastPos - curPos;
		Vector3 f = forward * dir.y;
		Vector3 r = right * dir.x;
		dir = f + r;
		transform.position = transform.position + dir * speed;
		
		lastPos = curPos;
		updateCallback?.Invoke();
	}
}
